import { baseUrl } from './env';
export const TokenKey = "authorized-token";
import qs from 'qs'

const noAuthWhiteList = ['/wx-login'];
class Http {
  request = (api, config = {},param=null,root=false) => {
    let requrl = api
    if(!root){
      requrl = `${baseUrl}${api}`
    }
    if(param ){
      requrl+=`?${qs.stringify(param)}`
    };
    return new Promise((resolve, reject) => {
      uni.request({
        url: requrl,
        ...config,
        header:{
          "Authorization": uni.getStorageSync(TokenKey) ,
          "content-type": "application/json" 
        },
        success(resp) {
          const { data } = resp;
          console.log(requrl,data)
          if(resp.statusCode!=200){
            reject(new Error(data.message))
            return
          }
          resolve(data);
        },
        fail(err) {
          console.error(requrl,err)
          reject(err);
        },
        complete() {
          setTimeout(()=>{
            uni.hideLoading(); 
          },1000)
        },
      });
    });
  };

  post(api,data){
    return this.request(`${api}`,{
      data,
      method:'post'
    })
  }
  postRoot(api,data){
    return this.request(`${api}`,{
      data,
      method:'post'
    },null,true)
  }
  getRoot(api,params){
    return this.request(`${api}`,null,params,true)
  }
  get(api,params){    
    return this.request(`/${api}`,null,params)
  }
  gql(query,variables){
    return this.request(`/graphql`,{
      method:'post',
      data:{ query:JSON.stringify(query), variables},
    })
  }

}
 
export default new Http();
